<template>
	<view>
		<uni-forms
			ref="formRef"
			:border="config.border"
			:labelWidth="config.labelWidth"
			:labelAlign="config.labelAlign"
			:labelPosition="config.labelPosition"
			:modelValue="formData"
		>
			<block v-for="(item, key) in columns" :key="key">
				<uni-forms-item :label="item.label" :required="item.required" :name="key">
				
					<view v-if="item.slot">
						
						<slot :name="key"></slot>
					</view>
					
					<view v-if="!item.slot">
						<!-- 文本框，密码输入框 -->
						<view v-if="['text', 'password'].indexOf(item.type) != -1" class="d-flex a-center" >
							<uni-easyinput
								@focus="closeTemplate()"
								:trim="true"
								:styles="{ disableColor: item.readonly ? '#FFF' : '' }"
								:primaryColor="CFG.color.primary"
								:maxlength="item.maxlength"
								:disabled="item.disabled || item.readonly"
								:type="item.type"
								v-model="formData[key]"
								:inputBorder="!config.border"
								:placeholder="item.placeholder"
							/>
						</view>
						
						<!-- 数字输入框 -->
						<view @click="keyboardFunc.onShow(key, item)" v-if="['number', 'car', 'card'].indexOf(item.type) != -1">
							<uni-easyinput
								:styles="{ disableColor: !item.disabled ? '#FFF' : '#e5e5e5' }"
								:trim="true"
								:primaryColor="CFG.color.primary"
								:disabled="true"
								:maxlength="item.maxlength"
								type="text"
								v-model="formData[key]"
								:inputBorder="!config.border"
								:placeholder="item.placeholder"
							/>
						</view>
						
						<!-- 选择框 -->
						<view @click="keyboardFunc.confirm" v-if="item.type == 'select'">
							<uni-data-select
								:styles="{ borderColor: !item.border ? '#FFF' : '#e5e5e5' }"
								:disabled="item.disabled || item.readonly"
								v-model="formData[key]"
								:localdata="item.range"
							/>
						</view>
						
						<!-- 时间选择器 -->
						<view @click="datetimePickerFunc.onShow(key, item)" v-if="['datetime', 'date', 'time', 'year-month', 'year'].indexOf(item.type) != -1">
							<uni-easyinput
								:styles="{ disableColor: !item.disabled ? '#FFF' : '#e5e5e5' }"
								:trim="true"
								:primaryColor="CFG.color.primary"
								:disabled="true"
								:maxlength="item.maxlength"
								type="text"
								v-model="formData[key]"
								:inputBorder="!config.border"
								:placeholder="item.placeholder"
							/>
						</view>
						
						<!-- 文本域 -->
						<view v-if="item.type == 'textarea'">
							<uv-textarea
							    @focus="closeTemplate()"
								:disabled="item.disabled || item.readonly"
								:maxlength="item.maxlength || -1"
								:readonly="item.readonly"
								:border="item.border || 'none'"
								:autoHeight="item.autoHeight"
								:height="item.height"
								:count="item.count"
								v-model="formData[key]"
								:placeholder="item.placeholder || '请输入内容'"
								:customStyle="{ backgroundColor: item.readonly ? '#fff' : '' }"
								:textStyle="{ color: item.readonly ? '#333' : '' }"
							></uv-textarea>
						</view>
						
					</view>
					
				
				</uni-forms-item>
			</block>
		</uni-forms>

		<!-- 数字输入框 -->
		<uv-keyboard
			ref="keyboardRef"
			@change="keyboardFunc.change"
			@backspace="keyboardFunc.backspace"
			@confirm="keyboardFunc.confirm"
			:mode="keyboardFunc.mode.value"
			:safeAreaInsetBottom="true"
			:overlay="false"
			:autoChange="true"
			:dotDisabled="keyboardFunc.dotDisabled.value"
		/>

		<!-- 日期选择器 -->
		<uv-datetime-picker
			ref="datetimePickerRef"
			v-model="datetimePickerFunc.formValue.value"
			:mode="datetimePickerFunc.mode.value"
			:confirmColor="CFG.color.primary"
			@confirm="datetimePickerFunc.confirm"
		/>
	</view>
</template>
<script>
import props from './props.js';

export default {
	name: 'wh-form',
	mixins: [props],
	setup(props) {
		const formRef = ref(null);
		const keyboardRef = ref(null);
		const datetimePickerRef = ref(null);
		const formData = ref({});
		const rules = ref({});
		const path = getCurrentPages()
		const storeKey = ref('')
		const isInit = ref(true)

		onMounted(() => {
			storeKey.value =  path[path.length - 1].route
	
			if(props.model.id){
				storeKey.value += '/' + props.model.id
				let res = uni.getStorageSync(storeKey.value)
					for (let key in props.columns) {
						formData.value[key] = res[key] || props.model[key];
					}
			}else{
				for (let key in props.columns) {
					formData.value[key] = props.model ? props.model[key] : '';
				}
			}
			
			formRef.value.setRules(props.columns);
			isInit.value = false // 初始化完成，将isInit设置为false，以避免在formData变化时再次初始化。
		});
		
	    // 监听formData的变化，更新model的值
        watch(() => formData.value, (newVal) => {
			if(!isInit.value){
				uni.setStorageSync(storeKey.value, newVal); // 存储到本地缓存中，key为当前页面的路径，value为formData的值。如果formData的id存在，则将id拼接到路径中，以避免id相同导致数据覆盖。
			}
        }, {deep: true});
        
   
		
		//阻止系统键盘弹出
		const hideSysKey=(event)=>{
			event.target.blur();	
		}


		//键盘相关逻辑
		const onKeyboard = () => {
			const mode = ref('number');
			const dotDisabled = ref(false);
			const formKey = ref(''); //当前输入框的key值，用于确定输入框的值，并赋值给formData.value[formKey.value]
			const formItem = ref({});

			//显示键盘
			const onShow = (key, item) => {
					
				// if (item.readonly == true || item.disabled == true) {
				// 	return;
				// }
				closeTemplate();
				formItem.value = item;
				mode.value = item.type;
				formKey.value = key;
				dotDisabled.value = item.dotDisabled;
				setTimeout(() => {
					keyboardRef.value.open();
				}, 500);
			};
			
			


			//写入
			const change = (e) => {
				if (!formData.value[formKey.value]) {
					formData.value[formKey.value] = '';
				}

				if (formItem.value.maxlength) {
					//限制长度，如果输入框有最大长度限制，则需要判断是否超过最大长度。
					if (formData.value[formKey.value].length < formItem.value.maxlength) {
						formData.value[formKey.value] += e;
					}
				} else {
					formData.value[formKey.value] += e;
				}
			};

			//退格
			const backspace = () => {
				if (formData.value[formKey.value].length) formData.value[formKey.value] = formData.value[formKey.value].slice(0, -1);
			};

			//确认
			const confirm = () => {
				keyboardRef.value.close(); //关闭键盘。
			};

			return { mode, dotDisabled, change, backspace, confirm, onShow };
		};
		const keyboardFunc = onKeyboard();

		//日期选择器相关逻辑
		const onDatetimePicker = () => {
			const mode = ref('number');
			const formKey = ref(''); //当前输入框的key值，用于确定输入框的值，并赋值给formData.value[formKey.value]
			const formItem = ref({});
			const formValue = ref(''); //日期选择器的值，用于确定日期选择器的值，并赋值给formData.value[formKey.value]
			const format=ref('') //日期选择器的格式，用于确定日期选择器的格式，并赋值给formData.value[formKey.value]的格式。
			
			
			//显示日期
			const onShow = (key, item) => {
				closeTemplate();
				formItem.value = item;
				formKey.value = key;
				
				switch(item.type){
					case 'datetime': //日期时间选择器，支持年、月、日、时、分、秒的显示和选择。
						format.value = item.format || "yyyy-mm-dd hh:MM:ss"
					break;
					case'date':
						format.value = item.format || "yyyy-mm-dd"
					break;
					case'time':
						format.value = item.format || "hh:MM:ss"
					break;
					case'year-month':
						format.value = item.format || "yyyy-mm"
					break;
					case'year':
						format.value = item.format || "yyyy"
					break;
				}
				
			

				//初始化日期选择器的值，如果输入框有值，则使用输入框的值，否则使用当前日期。
				formValue.value = formData.value[key] || new Date().getTime()
				mode.value = item.type;
				setTimeout(() => {
					datetimePickerRef.value.open();
				}, 100);
			};

			//确认
			const confirm = () => {
				formData.value[formKey.value] = uni.$uv.date(formValue.value,format.value)
				datetimePickerRef.value.close(); //关闭键盘。
			};

			return { mode, confirm, formValue, onShow };
		};

		const datetimePickerFunc = onDatetimePicker();

		const onSubmit = () => {
			keyboardFunc.confirm(); //关闭键盘。

			formRef.value
				.validate()
				.then((res) => {
					console.log('表单数据信息：', res);
				})
				.catch((err) => {
					console.log('表单错误信息：', err);
				});
		};

		const closeTemplate = () => {
			keyboardRef.value.close(); //关闭键盘。
			datetimePickerRef.value.close(); //关闭日期选择器。
		};

		return {
	
			hideSysKey,
			props,
			formRef,
			keyboardRef,
			datetimePickerRef,
			formData,
			rules,
			keyboardFunc,
			datetimePickerFunc,
			onSubmit,
			closeTemplate
		};
	}
};
</script>
